﻿using JumpKick.HttpLib;
using Newtonsoft.Json;
using SharpEncrypt4.Lib;
using SharpEncrypt4l_Lib;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Runtime.Caching;
using YiHaoHospitalPlatform.Model;

namespace YiHaoHospitalPlatform
{
    public sealed class CommitInspectInstance
    {
        #region 局部变量
        /// <summary>
        /// 检查数据缓存
        /// </summary>
        private static MemoryCache InspectCache = MemoryCache.Default;
        /// <summary>
        /// 要提交的检查列表
        /// </summary>
        private static List<Inspect> inspectList = new List<Inspect>();
        /// <summary>
        /// 公钥
        /// </summary>
        private static string publicKey;
        /// <summary>
        /// 平台接口地址
        /// </summary>
        private static string platformUrl;
        /// <summary>
        /// 平台分配的机构代码
        /// </summary>
        private static string orgId;
        /// <summary>
        /// 缓存时间
        /// </summary>
        private static int cacheMinutes = 600;
        /// <summary>
        /// 检索检查信息action
        /// </summary>
        private static Action QueryInspectAction;
        /// <summary>
        /// 成功action
        /// </summary>
        private static Action<string> LoopCommitAction = new Action<string>(commitInspect);
        /// <summary>
        /// 失败action
        /// </summary>
        private static Action<WebException> FailLoopCommitAction = new Action<WebException>(RetryCommitInspect);
        #endregion
        #region 单利模式
        private static readonly Lazy<CommitInspectInstance> instance = new Lazy<CommitInspectInstance>(() =>
        {
            if (publicKey == null)
            {
                publicKey = ConfigurationManager.AppSettings["publicKey"];
            }
            if (platformUrl == null)
                platformUrl = ConfigurationManager.AppSettings["platform_url"];
            if (orgId == null)
                orgId = ConfigurationManager.AppSettings["org_id"];
            cacheMinutes = int.Parse(ConfigurationManager.AppSettings["inspect_cache_minutes"]);
            return new CommitInspectInstance();
        });
        private CommitInspectInstance() { }
        public static CommitInspectInstance Instance
        {
            get
            {
                return instance.Value;
            }
        }
        #endregion
        /// <summary>
        /// 设置本地检索数据的action
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public CommitInspectInstance setQueryInspectAction(Action action)
        {
            QueryInspectAction = action;
            return Instance;
        }
        /// <summary>
        /// 向服务器提交数据，只需调用一次，内部会循环调用获取数据的方法
        /// </summary>
        /// <param name="patients">病人列表</param>
        /// <returns></returns>
        public bool StartCommitInspects(List<Inspect> inspects)
        {
            if (QueryInspectAction == null)
                throw new Exception("请先设置QueryInspectAction");
            if (inspects != null)
                //组织要提交的数据
                foreach (Inspect inspect in inspects)
                {
                    //判断缓存中是否有该数据
                    Inspect cache = InspectCache[inspect.SQDDM] as Inspect;
                    if (cache == null)
                    {
                        inspect.isNew = true;
                        inspectList.Add(inspect);
                        AddCache(inspect);
                    }
                    else if (!cache.Equals(inspect))
                    {
                        inspect.isNew = false;
                        inspectList.Add(inspect);
                        AddCache(inspect);
                    }
                }
            commitInspect(null);
            return true;
        }

        private static void RetryCommitInspect(WebException ex)
        {
            commitInspect(null);
        }
        /// <summary>
        /// 递归调用，向服务器逐条提交数据
        /// </summary>
        private static void commitInspect(string commitSuccess)
        {
            if (inspectList.Count > 0 && commitSuccess != null)
                inspectList.RemoveAt(0);
            if (inspectList.Count > 0)
            {
                string json = JsonConvert.SerializeObject(inspectList[0]);
                Console.WriteLine(json);
                string encryptPatient = EncryptProvider.RSAEncrypt(RSAKeyConvert.RSAPublicKeyJava2DotNet(publicKey), json);
                Http.Post(platformUrl).Form(new { orgId = orgId, data = encryptPatient })
                    .OnSuccess(LoopCommitAction)
                    .OnFail(FailLoopCommitAction)
                    .Go();
            }
            else
            {
                QueryInspectAction.BeginInvoke(null, null);
            }
        }

        /// <summary>
        /// 向缓存中添加数据
        /// </summary>
        /// <param name="department"></param>
        private void AddCache(Inspect inspect)
        {
            Inspect cache = InspectCache[inspect.SQDDM] as Inspect;
            if (cache != null)
                InspectCache.Remove(inspect.SQDDM);
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinutes);//取得或设定值，这个值会指定是否应该在指定期间过后清除
            InspectCache.Set(inspect.SQDDM, inspect, policy);
        }
    }
}
